package com.lsu.app.tool;

import io.jsonwebtoken.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author hjj
 * @date 2023/10/14 14:15
 */
public class jwtUtil {
    private static long time = 1000*60*60*24;//设置token存在时间为1天
    private static String signature = "financePlatform";//校验码
//    private static String localRole;//本地role
//    private static String username;//当前操作账号

    private static List<Integer> loginUserIds = new ArrayList<>();//记录当前登录的用户id

    public static void addLoginUserIds(Integer id){//用户登录
        loginUserIds.add(id);
    }
    public static void deleteLoginUserIds(Integer id){//用户登出
        loginUserIds.remove(id);
    }
    public static boolean containLoginUserIds(Integer id){//查询是否登录
       return loginUserIds.contains(id);
    }
    public static List<Integer> re(){
        return loginUserIds;
    }

    public static String createToken(Integer id,String role){
//        jwtUtil.setUsername(username);
//        jwtUtil.setLocalRole(role);
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //header
                .setHeaderParam("typ","JWT") //头信息
                .setHeaderParam("alg","HS256")
                //payload
                .claim("id",id)//载荷
                .claim("role",role)
                .setSubject("user-role") //加入主题
                .setExpiration(new Date(System.currentTimeMillis()+time)) //有效期
                .setId(UUID.randomUUID().toString()) //设置id
                //signature
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return jwtToken;
    }
    public static boolean checkToken(String token){
        if(token == null){
            return false;
        }
        try{
            //能解析成功，就说明token有效
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    //存储前端访问的token
//    public static void setLocalRole(String role){
//        localRole=role;
//    }
//
//    public static String getUsername() {
//        return username;
//    }
//
//    public static void setUsername(String username) {
//        jwtUtil.username = username;
//    }
//
//    //获取存储到本地的token
//    public static String getLocalRole(){
//        return localRole;
//    }


}
